import React, { Component } from 'react';
import ReacrDOM from 'react-dom'
import { Dialog, Grid, Input, Radio, Button,Form, Field, Feedback } from '@icedesign/base';
import IceContainer from '@icedesign/container';
import axios from 'axios';
import {hashHistory} from 'react-router';
import {
  FormBinderWrapper as IceFormBinderWrapper,
  FormBinder as IceFormBinder,
  FormError as IceFormError,
} from '@icedesign/form-binder';
import { enquireScreen } from 'enquire-js';
import {GET,POST,PUT} from '../../../../utils/public'

const { Row, Col } = Grid;
const { Group: RadioGroup } = Radio;
const FormItem = Form.Item;
const defaultValue = {
  keywords: '',
  type: 'post',
  content: '',
};

export default class EditCompany extends Component {
  static displayName = 'EditCompany';

  constructor(props) {
    super(props);
    this.field = new Field(this);    
    this.state = {
      visible: false,
      value: defaultValue,
      isMobile: false,
      adress:'',
      type:'',//dialog打开方式 edit 编辑， add 添加
      userID:null
    };
  }
  handleChildChange=(newState)=>{
    this.setState(newState)
  }

  componentDidMount() {
    this.enquireScreenRegister();
  }

  enquireScreenRegister = () => {
    const mediaCondition = 'only screen and (max-width: 720px)';

    enquireScreen((mobile) => {
      this.setState({
        isMobile: mobile,
      });
    }, mediaCondition);
  };

  onOpen=(record,type)=>{  
     //record: 编辑时record为当前行的数据记录，添加时为空
    //type: edit编辑 add 添加
    this.field.setValues({"companyName":"","adress":"","context":""})
    this.setState({"type":type,"id":""})
    if(type=="edit"){
      //编辑用户时，回显数据
      this.setState({"type":type,"id":record.id})      
    
      this.field.setValues({...record})
    }
    
    this.showDialog();
  }

  showDialog = () => {   
    //显示dialog 
    this.setState({
      visible: true,
    });
  };

  hideDialog = () => {
    //隐藏dialog
    this.field.reset(); //关闭dialog时，清空field;
    this.setState({
      visible: false,
    });
  };



  onSubmit = () =>{
    //保存
    this.field.validate((errors, values) => {
        // 提交当前填写的数据
        if(errors){
          return;
        }
        this.state.type=='edit'?this.onEditSave(values):this.onAddSave(values);
        
    });
    let type = this.state.type;
    this.field.getError()
    let values = this.field.getValues();
   
  }

  onEditSave = (values) =>{
    //编辑保存
    let id = this.state.id;
   let data = this.field.getValues();
   
    PUT(`api/company/${id}`,data)
        .then(res=>{
            if(!res){
                Feedback.toast.error('与服务器失去连接，稍后再试！');
            }else if(res.code == 200 && res.success){
                Feedback.toast.success('保存成功！');
                this.hideDialog();
                this.props.onSaveChange(true);
            }else if(res.code == 400){
                this.resolveError(res.errors)
            }else if(res.code==401 && res.msg=='请登录!'){
                Feedback.toast.error(`登录过期，${res.msg}`);
                setTimeout(()=>{
                  hashHistory.push('/login');
                },3000);
              }else{
                Feedback.toast.error(`网络出错了，${res.msg}`);
              }
        },error=>{
            Feedback.toast.error(`网络出错了，${error}`);
        })
   
  }


  onAddSave = (values) =>{
    //新增保存
    let data = this.field.getValues();
    POST('api/company',data)
        .then(res=>{
            if(!res){
                Feedback.toast.error('与服务器失去连接，稍后再试！');
            }else if(res.code == 200 && res.success){
                Feedback.toast.success('保存成功！');
                this.hideDialog();
                this.props.onSaveChange(true);
            }else if(res.code == 400){
                this.resolveError(res.errors)
            }else if(res.code==401 && res.msg=='请登录!'){
                Feedback.toast.error(`登录过期，${res.msg}`);
                setTimeout(()=>{
                  hashHistory.push('/login');
                },3000);
              }else{
                Feedback.toast.error(`网络出错了，${res.msg}`);
              }
        },error=>{
            Feedback.toast.error(`网络出错了，${error}`);
        })
  }


  onFormChange = (value) => {
    this.setState({
      value,
    });
  };
  resolveError=errors=>{
    //异常处理
    errors.forEach((item)=>{
      const { getError, setError, setErrors } = this.field;
      let name = item.field;
      let msg = item.message;
      setError(name, msg);
    })
  }

  render() {
    const { isMobile } = this.state;
    const simpleFormDialog = {
      ...styles.simpleFormDialog,
    };
    const formItemLayout = {
      labelCol: {
        fixedSpan: 10
      },
      wrapperCol: {
        span: 14
      }
    }
    const { init} = this.field;
    // 响应式处理
    if (isMobile) {
      simpleFormDialog.width = '300px';
    }

    return (
        <Dialog
          className="edit-company-dialog"
          style={simpleFormDialog}
          autoFocus={false}
          footerAlign="center"
          title="用户信息"
          {...this.props}
          onOk={this.onSubmit}
          onCancel={this.hideDialog}
          onClose={this.hideDialog}
          isFullScreen
          visible={this.state.visible}
        >
          <Form direction="ver" field={this.field}>
            <FormItem label="id" {...formItemLayout} style={styles.formitem}>
                <Input placeholder="" {...init("id")} />
            </FormItem >
            <FormItem label="公司名称" {...formItemLayout} >
              <Input placeholder="" {...init("companyName" ,
                    { rules: [
                        { required: true,message: "不能为空" },
                    // { min:5,max:20,message:'用户名5-20位'}
                    ]}
                    )}/>
            </FormItem >
            <FormItem label="地址" {...formItemLayout} >
              <Input placeholder="" {...init("address",
                    {rules:[ { required: true,message:"不能为空"},
                            //   {min:5,max: 22,message:'密码5-22位！'}     
                            ]}
                          )} />
            </FormItem >
{/*            
            <FormItem label="姓名" {...formItemLayout} >
              <Input placeholder="" {...init("name",{ rules: { required: true,message: "不能为空" }})}/>
            </FormItem >
            */}
           
            <FormItem label="备注说明"  {...formItemLayout}>
              <Input multiple placeholder="" {...init("comment")} />
            </FormItem>
          
            </Form>
         </Dialog>
    );
  }
}

const styles = {
  simpleFormDialog: { width: '640px' },
  dialogContent: {},
  formRow: { marginTop: 20 },
  input: { width: '100%' },
  formLabel: { lineHeight: '26px' },
  formitem:{ visibility:"hidden",display:"none"}
};
